package com.xyz.lockAndList;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author 肖咉卓
 * 限流：总共只有3个资源，当占满了后就不会再抢，等其他线程释放资源后才能继续抢
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //模拟资源类，有三个空车位
        Semaphore semaphore = new Semaphore(3);

        for (int i=1;i <= 6;i++){
         new Thread(() ->{
             try {
                 semaphore.acquire();
                 System.out.println(Thread.currentThread().getName()+"\t抢占了一个车位");
                 try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
                 System.out.println(Thread.currentThread().getName()+"\t开走了释放车位");
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }finally {
                 semaphore.release();
             }
         },String.valueOf(i)).start();
        }
    }
}
